import array

from DrissionPage._configs.chromium_options import ChromiumOptions
from DrissionPage._pages.chromium_page import ChromiumPage


def replace_variables(input_string, variables):
    for key, value in variables.items():
        placeholder = "${" + key + "}"
        input_string = input_string.replace(placeholder, value)
    return input_string


class HookPage(ChromiumPage):

    def __init__(self, addr_or_opts=None, tab_id=None, timeout=None):
        self.hook_js_list: list = []
        super().__init__(addr_or_opts, tab_id, timeout)

    def hook(self, hook_object: str, hook_value: str, intercept_str: str = ''):
        """

        :param hook_object: hook的对象
        :param hook_value:  要被hook的value
        :param intercept_str: 要被调试的内容所包含的字符（选填，不填写默认全部）
        (function () {
          'use strict';
          var cookieTemp = '';
          Object.defineProperty( {hook_object} , '{hook_value}', {
            set: function (val) {
              if (val.indexOf('{intercept_str}') != -1) {
                debugger;
              }
              console.log('Hook捕获到cookie设置->', val);
              cookieTemp = val;
              return val;
            },
            get: function () {
              return cookieTemp;
            },
          });
        })();
        执行的js操作如上图，会在页面调用前执行
        :return:
        """
        with open('hook', 'r') as file:
            script_template = file.read()
            _var = {
                "hook_object": hook_object,
                "hook_value": hook_value,
                "intercept_str": intercept_str
            }
            script_template = replace_variables(script_template, _var)
        js_id = self.add_init_js(script_template)
        self.hook_js_list.append(js_id)
        return js_id

    def remove_hook(self, js_id=None):
        """
        :param js_id:要移除的hook的js_id
        :return:
        """
        if not js_id:
            for i in self.hook_js_list:
                self.remove_init_js(i)
        else:
            self.remove_init_js(js_id)

    def block_url(self, url_regex=None, release_url=None):
        """
        阻塞请求
        :param url_regex:正则地址数组 ["*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp"]
        :param release_url:要放行地址数组
        :return:
        """
        if url_regex is None:
            url_regex = ["*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp"]
        if release_url is None:
            release_url = []
        self.run_cdp("Network.enable")
        self.run_cdp("Network.setBlockedURLs", urls=url_regex)
        # self.run_cdp("Network.Network.requestWillBeSent", documentURL="")



if __name__ == '__main__':
    page = HookPage()

    page.hook('document', 'cookie', '')
    page.block_url()
    page.get("https://www.baidu.com")

